package com.franklin.maven.localcleaner.api.swing.text;

import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

/**
 * 带有PlaceHolder功能的JTextFiled
 * @author Franklin
 * @since 2022/04/04 22:53
 */
public class PlaceHolderTextField extends JTextField {

    /**
     * placeHolder
     */
    private String placeHolder = "Please Input";

    public PlaceHolderTextField() {
        this.refresh();
        this.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {
                String input = PlaceHolderTextField.this.getText();
                if (StringUtils.equals(placeHolder,input)){
                    PlaceHolderTextField.this.setText(StringUtils.EMPTY);
                }
            }

            @Override
            public void focusLost(FocusEvent e) {
                String input = PlaceHolderTextField.this.getText();
                if (StringUtils.isBlank(input)){
                    PlaceHolderTextField.this.setText(placeHolder);
                }
            }
        });
    }

    public String getPlaceHolder() {
        return placeHolder;
    }

    public void setPlaceHolder(String placeHolder) {
        this.placeHolder = placeHolder;
        this.refresh();
    }

    /**
     * 获取真正输入的文本
     * @return
     */
    public String getInputText() {
        String input = super.getText();
        if (StringUtils.equals(placeHolder,input)){
            return StringUtils.EMPTY;
        }
        return input;
    }

    /**
     * 刷新
     */
    public void refresh(){
        this.setText(this.placeHolder);
    }
}
